﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SilverlightProgressFeedback.Web.ProgressFeedback
{
    public class Monitor
    {
        public const double MaxActionWaitTime = 0.5; // In minutes
        public const double MaxAge = 60.0; // In minutes

        private readonly Dictionary<Guid, ProgressInfo> _dictionary = new Dictionary<Guid, ProgressInfo>();

        public void Purge()
        {
            lock (this)
            {
                List<ProgressInfo> itemsToRemove =
                    _dictionary
                        .Values
                        .Where(
                            item => item.Age.TotalMinutes > MaxAge || item.TimeSinceLastAction.TotalMinutes > MaxActionWaitTime)
                    .ToList();

                itemsToRemove.ForEach(item => _dictionary.Remove(item.ProgressFeedbackKey));
            }
        }

        public ProgressInfo RegisterNewProgressProcess(Guid progressFeedbackKey)
        {
            Purge();

            ProgressInfo infoHolder = new ProgressInfo(progressFeedbackKey);
            lock (this)
            {
                _dictionary.Add(progressFeedbackKey, infoHolder);
            }
            return infoHolder;
        }

        public ProgressInfo GetInfo(Guid key)
        {
            lock (this)
            {
                ProgressInfo info;
                if (_dictionary.TryGetValue(key, out info))
                {
                    info.ActionPerformed();
                    return info;
                }
                return null;
            }
        }
    }
}